#' 增加eaf
#'
#' @param dat harmonize后的dat
#' @param what exposure或者outcome
#' @param pop 人种，默认为EUR
#'
#' @return 增加了eaf后的dat，用于计算R2
#' @export
#'
#' @examples
#'
#' \dontrun{
#' dat<-U4_add_eaf(dat)
#' }
#'
#'
#'
U4_add_eaf<- function(dat, what = "exposure" ,pop = "EUR"){
  if(what == "exposure" ){
  index <-  which( is.na( dat$eaf.exposure))
  if(length(index)==0){
    message("\n\n所有SNP的暴露数据的eaf都是完整的，不需要填充\n\n")
    return(dat)
  }
  message( paste0(length(index),'\n\n个SNP在暴露数据没有eaf,查询中......') )

  index_SNP<-unique(dat$SNP[index])

  pb <- progress::progress_bar$new(total = length(index_SNP))

  for (i in 1:length(index_SNP)) {
    dat$eaf.exposure[which(dat$SNP==index_SNP[i])]<- retry(operation =find_eaf,args = list(index_SNP[i],pop = pop),max_retries = 10 )
    pb$tick()
  }
  index <-  which( is.na( dat$eaf.exposure))
  if(length(index)>0){
    message( paste0("还有",length(index),'个SNP在暴露数据没有eaf，填充为0.5') )
    dat$eaf.exposure[index]<-0.5}else{
      message("所有SNP在暴露数据的eaf都填充了")
    }
  }

  if(what == "outcome" ){
    index <-  which( is.na( dat$eaf.outcome))
    if(length(index)==0){
      message("\n\n所有SNP的结局数据的eaf都是完整的，不需要填充")
      return(dat)
    }
    message( paste0(length(index),'个SNP在结局数据没有eaf,查询中......') )

    index_SNP<-unique(dat$SNP[index])

    pb <- progress::progress_bar$new(total = length(index_SNP))

    for (i in 1:length(index_SNP)) {
      dat$eaf.outcome[which(dat$SNP==index_SNP[i])]<- retry(operation =find_eaf,args = list(index_SNP[i],pop = pop),max_retries = 10 )
      pb$tick()
    }
    index <-  which( is.na( dat$eaf.outcome))
    if(length(index)>0){
      message( paste0("还有",length(index),'个SNP在结局数据没有eaf，填充为0.5') )
      dat$eaf.outcome[index]<-0.5}else{
        message("所有SNP在结局数据的eaf都填充了")
      }
  }

  return(dat)
}

find_eaf<-function(SNP,pop = "EUR"){

  server <- "http://rest.ensembl.org/variation/Homo_sapiens/%s?content-type=application/json;pops=1"

  server <- sprintf(server,SNP)

  res <- httr::GET(server)

  httr::stop_for_status(res)

  res_pop <- jsonlite::fromJSON(jsonlite::toJSON(httr::content(res)))$populations

  eaf <- subset(res_pop,population == paste0("1000GENOMES:phase_3:",pop) )

  if(nrow(eaf)==0){ eaf.final <- NA }else{
    eaf.final <- eaf$frequency[1][[1]]
  }
  return(eaf.final)
}
